﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
public delegate void AddHandler(int a, int b);

namespace Framework
{
    class Test
    {
        static void Main()
        {

            const int BufferSize = 8192;    // 缓存大小，8192字节
            Console.WriteLine("Server is running ... ");
            var ip = new IPAddress(new byte[] { 127, 0, 0, 1 });
            var listener = new TcpListener(ip, 8500);
            listener.Start();           // 开始侦听
            Console.WriteLine("开始侦听 ...");
            Console.WriteLine("**********SyncInvokeTest**************");
            var handler = new AddHandler(Send);
            handler.BeginInvoke(1, 2, null, null);
            Console.WriteLine("执行监听  ... ... ...");
            // 获取一个连接，中断方法
            int i = 0;
            while (true)
            {
                TcpClient remoteClient = listener.AcceptTcpClient();
                // 打印连接到的客户端信息
                Console.WriteLine("Client Connected！{0} <-- {1}",
                    remoteClient.Client.LocalEndPoint, remoteClient.Client.RemoteEndPoint);
                // 获得流，并写入buffer中
                NetworkStream streamToClient = remoteClient.GetStream();
                var buffer = new byte[BufferSize];
                int bytesRead = streamToClient.Read(buffer, 0, BufferSize);
                Console.WriteLine("Reading data, {0} bytes ...", bytesRead);
                // 获得请求的字符串
                string msg = Encoding.Unicode.GetString(buffer, 0, bytesRead);
                Console.WriteLine("Received: {0}", msg);
                Console.WriteLine("第{0}次", i);
                i++;
            }
        }
        static void Send(int a, int b)
        {

            Console.WriteLine("Client Running ...");
            for (int i = 0; i < 5; i++)
            {
                Thread.Sleep(2000);
                TcpClient client;
                try
                {
                    client = new TcpClient();
                    client.Connect("localhost", 8500);      // 与服务器连接
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    return;
                }
                // 打印连接到的服务端信息
                Console.WriteLine("Server Connected！{0} --> {1}",
                    client.Client.LocalEndPoint, client.Client.RemoteEndPoint);
                const string msg = "\"Welcome To TraceFact.Net\"";
                NetworkStream streamToServer = client.GetStream();
                byte[] buffer = Encoding.Unicode.GetBytes(msg);     // 获得缓存
                streamToServer.Write(buffer, 0, buffer.Length);     // 发往服务器
                Console.WriteLine("Sent: {0}", msg);
            }



        }
    }



}
